// Package middleware
// Author liuzhiyong
// Date 2023/11/16
// Description 基础的中间件 做日志打印 和 recover
package middleware

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"runtime/debug"
	"strings"
	"time"
)

// CustomResponseWriter 自定义的ResponseWriter 用于获取响应数据
type CustomResponseWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer // 响应体缓存
}

// Write
func (w CustomResponseWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

// WriteString
func (w CustomResponseWriter) WriteString(s string) (int, error) {
	w.body.WriteString(s)
	return w.ResponseWriter.WriteString(s)
}

// GinLogger 日志中间件
func GinLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		logger.Info(fmt.Sprintf("请求开始: %s", path),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
		)
		// 替换运来的Writer
		blw := &CustomResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		c.Writer = blw
		c.Next()
		logger.Info(fmt.Sprintf("请求结束: %s", path),
			zap.Int("status", c.Writer.Status()),
			zap.String("path", path),
			zap.String("response", blw.body.String()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Int64("cost", time.Since(start).Microseconds()),
		)

	}
}

// GinRecovery  recover掉项目可能出现的panic
// param: logger
// param: stack 是否打印堆栈信息
func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			// 执行recover() 捕获异常
			if err := recover(); err != nil {
				//检查是否有断开的连接，因为这并不是一个真正需要进行紧急堆栈跟踪的条件。
				var brokenPipe bool
				// 如果异常时net.OpError类型 ==> 转为 对应类型 err.() 类型断言的写法, 判断类型, 转换类型
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") ||
							strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}
				// 将http请求转换成字节切面, 第二个布尔类型的参数表示是否包括请求体, 为false的话表示只包括请求头
				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				if brokenPipe {
					logger.Error(c.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					// If the connection is dead, we can't write a status to it.
					c.Error(err.(error)) // nolint: errcheck
					c.Abort()
					return
				}
				if stack {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}
				c.AbortWithStatus(http.StatusInternalServerError)
				// c.JSON(200, gin.H{"code": 1, "msg": "出错啦"})
				// return
			}
		}()
		c.Next() // 调用后续的逻辑
	}
}
